var params = getUrlParams();
var USER_INFO = "wdk_login_info";
var MENU_CODE="wdk_current_menu_code";
$(function(){
    $('#sidebar a').each(function(){
        $(this).on('click',function(){
            $('#sidebar a').removeClass('css-navbar');
            $(this).addClass('css-navbar');
        })
    })
})

function HashTable()
{
    var size = 0;
    var entry = new Object();

    this.add = function (key , value)
    {
        if(!this.containsKey(key))
        {
            size ++ ;
        }
        entry[key] = value;
    }

    this.getValue = function (key)
    {
        return this.containsKey(key) ? entry[key] : null;
    }

    this.remove = function ( key )
    {
        if( this.containsKey(key) && ( delete entry[key] ) )
        {
            size --;
        }
    }

    this.containsKey = function ( key )
    {
        return (key in entry);
    }

    this.containsValue = function ( value )
    {
        for(var prop in entry)
        {
            if(entry[prop] == value)
            {
                return true;
            }
        }
        return false;
    }

    this.getValues = function ()
    {
        var values = new Array();
        for(var prop in entry)
        {
            values.push(entry[prop]);
        }
        return values;
    }

    this.getKeys = function ()
    {
        var keys = new Array();
        for(var prop in entry)
        {
            keys.push(prop);
        }
        return keys;
    }

    this.getSize = function ()
    {
        return size;
    }

    this.clear = function ()
    {
        size = 0;
        entry = new Object();
    }
}

function getUrlParam(name) {

	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = window.location.search.substr(1).match(reg);  //匹配目标参数
	if (r != null) return unescape(r[2]); return null; //返回参数值
}

function checkReturnStatus(status){
	if(status == 500){
		alert("操作失败");
		return false;
	}else{
		alert("操作成功");
		return true;
	}
}

function getToday() { 
	var now = new Date();
	var today = now.getFullYear()+"-";
	if(now.getMonth() > 8){
		today += (now.getMonth()+1)+"-";
	}else{
		today += "0"+(now.getMonth()+1)+"-";
	}
	if(now.getDate() > 9){
		today += now.getDate();
	}else{
		today += "0"+now.getDate();
	}
	return today;
} 

function formatDate(date) {
    var d = date,
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear(),
        hour = ''+d.getHours(),
        min = ''+ d.getMinutes(),
        sec = ''+d.getSeconds();
    if(month.length < 2) month = '0' + month;
    if(day.length < 2) day = '0' + day;
    if(hour.length < 2) hour = '0' + hour;
    if(min.length < 2) min = '0' + min;
    if(sec.length < 2) sec = '0' + sec;
    var s_date = [year, month, day].join('-');
    var s_time = [hour, min, sec].join(':');
    return s_date + " " + s_time;
}

function getUndefined (obj){
	return (typeof obj == "undefined" ) ? "" : obj;
}



function zero2null(num){
	if(num == 0){
		return "";
	}
	return num;
}

function toPercent(data){
    var strData = parseFloat(data)*10000;
    strData = Math.round(strData);
    strData/=100.00;
    var ret = strData.toString()+"%";
    return ret;
}

//四舍五入，保留位数为roundDigit     
function formatDigit(numberRound){   
	var roundDigit = 2;
	if   (numberRound>=0)   {   
		var   tempNumber   =   parseInt((numberRound   *   Math.pow(10,roundDigit)+0.5))/Math.pow(10,roundDigit);   
		return   tempNumber;   
	}  else  {   
		numberRound1=-numberRound   
		var   tempNumber   =   parseInt((numberRound1   *   Math.pow(10,roundDigit)+0.5))/Math.pow(10,roundDigit);   
		return   -tempNumber;   
	}   
}

/**
 * 举例： "tableContent", "/cabinetManager/listCabinet.json", req_data, 
			[
				{field: "id", isCheckbox: true},  //复选
				{field: "id", isRadio: true},     //单选
		        {field: "code", isLink: true, href: "/basic/editCabinet?id={0}", param: ["id"]},
		        {field: "warehouseName"},
		        {field: "statusText"},
		        {field: "maxCapacity"},
		        {field: "rackPriority"},
		        {field: "pickPriority"},
		        {field : "详情", isOperateCol : true, href: "javascript:workBatchDetail({0})", param: ["id"]} --操作列
			], listCabinet
 * @param id  tbody的ID
 * @param seq_url  请求URL
 * @param seq_data 请求数据
 * @param fieldArr 需要显示的字段列表
 * @param callback 回调函数对象（pageCallback/popCallback）
 * 
 */
function listData(id, seq_url, seq_data, fieldArr, callback){
	$.ajax( {    
		url: seq_url,
		data: seq_data,    
		dataType: "json",    
		success: function(data) {  
			if (data.code != 200){
				alert(data.msg);
				return;
			}
			var div = "";
			$.each(data.info, function(i, item) {
				div += generateTr(fieldArr, item);
			});
			$("#" + id).html(div);
			if (!!callback){
				if (!!callback.pageCallback){
					paginationHandler(data.info.totalNum, data.info.index, data.info.num, callback.pageCallback);
				}
				
				if (!!callback.popCallback){
					callback.popCallback();
				}
			}
		}   
	});
}

//生成表格中的行信息
function generateTr(fieldArr, item){
	var tr = '<tr class="odd gradeX">';
	var arr_len = fieldArr.length;
	for (var i = 0; i < arr_len; i++){
		var obj = fieldArr[i];
		if (!!obj.isRadio){
			tr += '<td><input type="radio" name="radioName" value=' + getUndefined(item[obj.field]) + '></input></td>';
		}else if (!!obj.isCheckbox){
			tr += '<td><input type="checkbox" value=' + getUndefined(item[obj.field]) + '></input></td>';
		}else if (!!obj.isLink){
			tr += '<td><a href='+ getHref(obj, item) + '>' + getUndefined(item[obj.field]) + '</a></td>';
		}else if (!!obj.isOperateCol){
			tr += '<td><a href='+ getHref(obj, item) + '>' + obj.field + '</a></td>';
		}else if (!!obj.isButton){
			var buttonArr = obj.field;
			var buttonHtml = getButton(buttonArr,item);
			tr += buttonHtml;
		}else{
			tr += '<td>' + getUndefined(item[obj.field]) + '</td>';
		}
	}
	tr += "</tr>";
	return tr;
}

function getButton(buttonArr,item){
	var arr_len = buttonArr.length;
	var buttonHtml="<td>";
	for(var i = 0; i < arr_len; i++) {
		var obj = buttonArr[i];
		buttonHtml += '<a href='+ getHref(obj, item) + '><button class="btn btn-info btn-addlistlast" type="button">' + obj.text + '</button></a>';
	}
	buttonHtml +="</td>";
	return buttonHtml;
}

//获取链接信息
function getHref(obj, item){
	var href = obj.href;
	if (!!obj.param){
		var len = obj.param.length;
		for (var y = 0; y < len; y++){
			var paramName = obj.param[y];
			href = href.replace("{" + y +"}",  item[paramName]);
		}
	}
	return href;
}


/**
 * 获取数据
 * @param exclude 需要排除的条件，["a","b"]
 */
function getMetaData(id,excludes){
	if($('#'+id).length==0) return;
	var result={};
	//获取所有有id属性的控件
	var pros = $('#'+id).find("[id]");
	$.each(pros,function(i,item){
		var pro = $(item).attr("id");
		//排除指定的条件
		if(!excludes || !excludes.contains(pro)){
			result[pro]=$(item).val();
		}
	})
	return result;
}

//分页处理
function paginationHandler(total, index, size, callbackFun){
    $("#Pagination").pagination(total, { 
       callback: function pageCallback(page_id, jq){
    		if(jq.length > 0){
    			clearSelectedItem();
    			callbackFun(page_id);
    		}
       }, 
       prev_text: '< 上一页', 
       next_text: '下一页 >', 
       items_per_page: size, 
       num_display_entries: 6, 
       current_page: index, 
       num_edge_entries: 2 
 	});
}

//清除选中项
function clearSelectedItem(){
	$("#selectAll").prop("checked", false);
	$("#tableContent input[type='checkbox']:checked").each(function(i, item){
		$(item).prop("checked", false);
	});
}

Array.prototype.contains = function(ele) {
	var flag = false;
	for (var i = 0; i < this.length; i++) {
		if (this[i] === ele) {
			flag = true;
		}
	}
	return flag;
}

Array.prototype.remove = function(ele) {
	var flag = false;
	for (var i = 0; i < this.length; i++) {
		if (this[i] === ele) {
			this.splice(i,1);
		}
	}
}

Array.prototype.isRepeat = function(){
	var flag = false;
	var hash = {};  
    for(var i in this) {  
        if(hash[this[i]]) {
        	flag = true;
        } 
        hash[this[i]] = true;  
    }  
    return flag;
}

/**
 * 获取数据
 * @param exclude 需要排除的条件，["a","b"]
 */
function getMetaData(id,excludes){
	if($('#'+id).length==0) return;
	
	var result={};
	
	//获取所有有id属性的控件
	var pros = $('#'+id).find("[name]");
	$.each(pros,function(i,item){
		var pro = $(item).attr("name");
		//排除指定的条件
		if(!excludes || !excludes.contains(pro)){
			result[pro]=$(item).val();
		}
	})
	
	return result;
}

function getUrlParams(){
	var params = {};
	var search = window.location.search.substr(1);
	if(!!search){
		var arr = search.split("&");
		for(var i=0;i<arr.length;i++){
			var arr2 =  arr[i].split("=");
			params[arr2[0]] = arr2[1];
		}
		return params;
	}
	return null;
}

function getDataById(id,seq_url, back_url,func){
	$.ajax({
		url: seq_url,
		data: {
			id: id
		},
		dataType: "json",
		async: false,
		success: function(data){
			if (data.code != 200){
				window.location.href = back_url;
			}
			var obj = data.info;
			for(item in obj){
				$("#"+item).val(obj[item]);
				if($("#"+item).val() == "" || !!$("#"+item).val()){
					$("#"+item).html(obj[item]);
				}
			}
			if(!!func){func(obj)};
		}
	});
}


function saveOrUpdateData(seq_url, back_url,data){
	$.ajax( {    
		url: seq_url,
		data: data,    
		dataType: "json",    
		success: function(data) {  		
			if (data.code != 200){
				alert(data.msg);
			}else{
				window.location.href = back_url;
			}
		}   
	});
}



function localGet(key){
	return JSON.parse(window.localStorage.getItem(key));
}

function localPut(key,value){
	window.localStorage.setItem(key,  JSON.stringify(value));
}

function localClear(prefix){
	var storage = window.localStorage;
	var deleteItems = [];
	for (var i = 0, len = storage.length; i < len; i++) {
		var key = storage.key(i);
		if(key.startWith(prefix)){
			deleteItems.push(key);
		}
	}
	for(var j = 0; j < deleteItems.length; j++){
		storage.removeItem(deleteItems[j]);
	}
	
}

String.prototype.startWith = function(s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substr(0, s.length) == s)
		return true;
	else
		return false;
	return true;
}

String.prototype.endWith=function(str){
	if (str == null || str == "" || this.length == 0
			|| str.length > this.length)
		return false;
	if (this.substring(this.length - str.length) == str)
		return true;
	else
		return false;
	return true;
}

function loadSysInfo(){
	var sysInfo = localGet('wdk_sys_info');
	
	var sysText = "系统ID：<span>" + sysInfo.id + "</span>" +
				  "系统名称：<span>" + sysInfo.name + "</span>" +
				  "系统CODE：<span>" + sysInfo.code + "</span>" +
				  "创建时间：<span>" + sysInfo.gmtCreate + "</span>" +
				  "最后更新时间：<span>" + sysInfo.gmtModified + "</span>" +
				  "更新人：<span>" + sysInfo.operatorName + "</span>";
	$("#sysInfo").html(sysText);
}

function InitializationIndex(){
	$.ajax({
			url: '/IndexTreeManager/indexTreeCreate.json',
			dataType: 'json',
		})
		.done(function(data) {
			var navList = [],
				sideBarList = []
			navList = $.map(data, function(item, index) {
					return '<li><a href="' + item.url + '">' + item.name + '</a></li>'
				}).join('')
				//一级菜单
			$('.nav-collapse .nav:last-child').html(navList)
				//获取是否拥有二级菜单 ==> [data.info.children[].children]

			// var siderBarObj  = data.filter(function(item, index) {
			//     return item.children && item.children.text == location.pathname.substring(1);
			// })[0]
			var siderBarObj = data[0]
				// console.log(JSON.stringify(siderBarObj))
			if (siderBarObj) {
				//是否含有三级惨淡
				var siderBarHtml = $.map(siderBarObj.children, function(item, index) {
						var thirdMenu = ''
						if (!!item.children.length) {
							thirdMenu = $.map(item.children, function(item2, index2) {
								return '<li role="presentation"><a role="menuitem" tabindex="-1" href="' + item2.url + '">' + item2.name + '</a></li>'
							}).join('')

							return '<li class="dropdown">' +
								'   <a href="' + item.url + '" class="dropdown-toggle" role="button" data-toggle="dropdown"><i class="icon-chevron-right"></i>' + item.name + '</a>' +
								'   <ul class="dropdown-menu right" role="menu" aria-labelledby="drop4">' +
								thirdMenu +
								'   </ul>'
							'</li>'
						} else return '<li>' +
							'   <a href="' + item.url + '">配送员绩效表</a>' + item.text +
							'</li>'
					}).join('') // 返回祖父穿
				$('#sidebar') && $('#sidebar ul').empty().html(siderBarHtml)
				$('.dropdown').hover(function(e) {
					$(e.target).trigger('click')
				})
			}
		})
		.fail(function(e) {
			console.log('获取数据失败');
		})

}
//InitializationIndex();

function linkTo(href){
	location.href = href;
}

$(document).ready(function() {
	//错误信息提示框tip
	var tipsContent = $(".tips-content").text();
	if(tipsContent !="" && tipsContent != null){
		$(".tips-warning").show();
	};	
	//模拟下拉
	$(".select").each(function(){
		var s=$(this);
		var z=parseInt(s.css("z-index"));
		var dt=$(this).children("dt");
		var dd=$(this).children("dd");
		var _show=function(){
			dd.slideDown(200);
			s.css("z-index",z+1);
			$("#arrow").addClass("arrow-up");
		};   //展开效果
		var _hide=function(){
			dd.slideUp(200);
			s.css("z-index",z);
			$("#arrow").removeClass("arrow-up");
			};    //关闭效果
		dt.click(function(){
			dd.is(":hidden")?_show():_hide();
			});
		dd.find("li").click(function(){
			dt.html($(this).html());
			_hide();			
			var items_per_page = $(".select dt span").text();
			$("#num").val(items_per_page);
			listStockRecord(0);
			}); 
		$("body").click(function(i){ 
			!$(i.target).parents(".select").first().is(s) ? _hide():"";
			});
	})
});

function getJsonDataNotEmpty(param,name,value){
	
	if(value==null || value.trim()=="")
	{
		return param;
	}
	else 
	{
		if(param.indexOf(":")>-1)
			return param+","+name+":"+value;
		else
			return param+name+":"+value;
	}
}
function getJsonDataNotNull(param,name,value){
	
	if(value==null)
	{
		return param;
	}
	else 
	{
		if(param.indexOf(":")>-1)
			return param+","+name+":"+value;
		else
			return param+name+":"+value;
	}
}